package cc.ufinity.networkdiagnose.widget;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.app.Dialog;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.wifi.ScanResult;
import android.os.Handler;
import android.os.Message;
import android.view.Display;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.AnimationUtils;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.AdapterView.OnItemClickListener;
import cc.ufinity.networkdiagnose.adapter.APListAdapter;
import cc.ufinity.networkdiagnose.adapter.SortButtoniListAdapter;
import cc.ufinity.networkdiagnose.app.GlobalApp;
import cc.ufinity.networkdiagnose.manager.APInfo;
import cc.ufinity.networkdiagnose.manager.ChinaNetAccount;
import cc.ufinity.networkdiagnose.manager.ChinaUnicomAccount;
import cc.ufinity.networkdiagnose.manager.DBManager;
import cc.ufinity.networkdiagnose.manager.FTPConfig;
import cc.ufinity.networkdiagnose.manager.MessageWhat;
import cc.ufinity.networkdiagnose.manager.RandomGUID;
import cc.ufinity.networkdiagnose.manager.Task;
import cc.ufinity.networkdiagnose.manager.TaskConfig;
import cc.ufinity.networkdiagnose.manager.TelManager;
import cc.ufinity.networkdiagnose.manager.WlanManager;
import cc.ufinity.networkdiagnose.manager.Task.FTPTask;
import cc.ufinity.networkdiagnose.manager.Task.HttpTask;
import cc.ufinity.networkdiagnose.manager.Task.PingTask;
import cc.ufinity.networkdiagnose.view.R;
import cc.ufinity.networkdiagnose.widget.GeneralTestWidget.APcompare;

public class RssiWidget extends GeneralTestWidget {

	private Handler handler;
	private Activity ctx;
	private TelManager tm;
	private WlanManager wlanManager;
	private ListView wifiView;
	private LinearLayout phoneLayout;
	private Button btnBack;
	private Button btSort;
	private SimpleAdapter adapter;
	
	private final static int SSID = 1;
	private final static int MAC = 2;
	private final static int LEVEL = 3;
	private final static int CHANNLE = 4;
	private int flag = LEVEL;
	final class APcompare implements Comparator<ScanResult> {

		private int flag;
		public APcompare(int flag) {
			this.flag = flag;
		}
		@Override
		public int compare(ScanResult p1, ScanResult p2) {
			// TODO Auto-generated method stub
			
            if(flag == SSID) {
            	return (p1.SSID).compareToIgnoreCase(p2.SSID);
            } else if(flag == MAC) {
            	return (p1.BSSID).compareToIgnoreCase(p2.BSSID);
            } else if(flag == LEVEL) {
            	if((p1.level) > (p2.level)) {
            		return -1;
            	} else if((p1.level) == (p2.level)) {
            		return 0;
            	} else {
            		return 1;
            	}
            } else if(flag == CHANNLE) {
            	if((p1.frequency) > (p2.frequency)) {
            		return 1;
            	} else if((p1.frequency) == (p2.frequency)) {
            		return 0;
            	} else {
            		return -1;
            	}
            }
			
            return 0;

		}
		
	}

	public RssiWidget(Activity context) {
		super(context);
		inflate(context, R.layout.rssi_widget, this);
		this.ctx = context;
		wifiView = (ListView) this.findViewById(R.id.wifiListView); 
		phoneLayout = (LinearLayout) this.findViewById(R.id.myPhoneInfo);
		btSort = (Button)this.findViewById(R.id.rssi_wifi_list_sort);
		btnBack = (Button) this.findViewById(R.id.rssi_btnback);
		wlanManager = new WlanManager(ctx);
		wlanManager.setFlag(flag);
		
		
		
		final Handler hand = new Handler() {

			@Override
			public void handleMessage(Message msg) {
				System.out.println("msg.arg1-----------"+msg.arg1 );
				switch(msg.arg1){
				case 0:
					flag = LEVEL;
					btSort.setText("默    认");
					break;
				case 1:
					flag = SSID;
					btSort.setText("S S I D");
					break;
				case 2:
					flag = MAC;
					btSort.setText("MAC地址");
					break;
				case 3:
					flag = LEVEL;
					btSort.setText("信号强度");
					break;
				case 4:
					flag = CHANNLE;
					btSort.setText("信    道");
					break;
			}
				wlanManager.setFlag(flag);
				List<ScanResult> scanResultTemp = new ArrayList<ScanResult>();
				scanResultTemp = wlanManager.getScanResults();
				sort(scanResultTemp);
				super.handleMessage(msg);
			}
        	
        };
		
		btSort.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				showSortButton(hand);
			}
		});
		btnBack.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				//back(ctx);
				switch(GlobalApp.nowNetType) {
				case 1:
					ctx.setContentView(new TestWidget_Wlan(ctx));
					break;
				case 2:
					ctx.setContentView(new TestWidget_TD(ctx));
					break;
				case 3:
					ctx.setContentView(new TestWidget_GSM(ctx));
					break;
				default:
					break;
				}
			}
		});
		handler = new Handler() {
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case MessageWhat.TEL_STATE_SUCCESS:
					//updateTel();
					break;
				case MessageWhat.WIFI_RECEIVE_LIST:
					updateWifi();
					dismissMessageDialog();
					if(ctx.getIntent().getIntExtra(MessageWhat.INDEX_RssiWidget_WIDGET, 0) == 1) {
					//	readyBegin();
					}
					break;
				}
			}
		};

		tm = new TelManager(ctx);
		tm.setHandler(handler);
		wlanManager.setHandler(handler);
		start();
	}

	private void start() {
		this.showMessageDialog(ctx, "正在进行RSSI测试...");
		wlanManager.startScan();
	}
	private void readyBegin() {
		new Thread() {
			public void run() {
				try {
					Thread.sleep(20 * 1000);
				} catch (InterruptedException e) {}
				wlanManager.startScan();
			}
		}.start();
	}

/*	private void updateTel() {
		phoneLayout.removeAllViews();
		TextView tv = new TextView(ctx);
		LayoutParams lp = new LayoutParams(
				LinearLayout.LayoutParams.FILL_PARENT,
				LinearLayout.LayoutParams.WRAP_CONTENT);
		lp.setMargins(15, 5, 5, 5);
		tv.setLayoutParams(lp);
		tv.setText("网络类型: " + tm.getNetworkType());
		phoneLayout.addView(tv);
		tv = new TextView(ctx);
		tv.setLayoutParams(lp);
		tv.setText("BER: " + tm.getBER() + "\n信号强度: " + tm.getStrSignalStrength()+" dBm");
		phoneLayout.addView(tv);
	}*/

	private void updateWifi() {
		List<Map<String, Object>> data = wlanManager.getWifiList();/*
		data = new ArrayList<Map<String,Object>>();
		data.add((Map<String, Object>) (new HashMap<String, Object>()).put("ssid", "sdfsd"));
		data.add((Map<String, Object>) (new HashMap<String, Object>()).put("mac","sdfsd"));
		data.add((Map<String, Object>) (new HashMap<String, Object>()).put("level", "23"));
		data.add((Map<String, Object>) (new HashMap<String, Object>()).put("img", "xh5.png"));*/
		if(data.size() > 0) {
			adapter = null;
			 adapter = new SimpleAdapter(ctx, data,
					R.layout.rssi_list_widget, new String[] { "ssid", "mac", "img",
							"level","xindao"}, new int[] { R.id.wifi_ssid, R.id.wifi_mac,
							R.id.wifi_img, R.id.wifi_level ,R.id.wifi_xindao});
			wifiView.setAdapter(adapter);
		}
		
	}
	
	 public int calcSNR(int pl, int pn) {
	        // double snr = Math.abs(pl) / pn;
	        // snr = 10 * Math.log10(snr);
	        int snr = pl - pn;
	        return snr;

	    }
	
	private void sort(List<ScanResult>  scanResults){
		APcompare cl = new APcompare(flag);
		
        Collections.sort(scanResults, cl);
        
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        DBManager db = new DBManager((Activity) ctx);
        List<TaskConfig> tasks = db.getTask();
        db.release();
        for (ScanResult result : scanResults) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("ssid", result.SSID);
            map.put("mac", result.BSSID);
            map.put("level", result.level + " dBm");
            map.put("xindao",getFrequency( result.frequency));
            map.put("snr", calcSNR(wlanManager.getCdmaDbm(), result.level));
            if (wlanManager.task != null) {
               /* if (db.taskFinished(tasks, result.BSSID, String.valueOf(wlanManager.task.id))) {
                    map.put("img", R.drawable.lock);
                    map.put("lock", "true");
                } else {
                    map.put("lock", "false");*/
                    
                   if(result.level<-85){
                	   map.put("img", R.drawable.xh1);
                   }else if(result.level<-75){
                	   map.put("img", R.drawable.xh2);
                   }else if(result.level<-65){
                	   map.put("img", R.drawable.xh3);
                   }else if(result.level<-55){
                   		map.put("img", R.drawable.xh4);
                   }else if(result.level<-45){
                	   map.put("img", R.drawable.xh5);
                   }else{
                	   map.put("img", R.drawable.xh6);
                   }
               // }
            } else {
               // map.put("lock", "false");
                
               if(result.level<-85){
            	   map.put("img", R.drawable.xh1);
               }else if(result.level<-75){
            	   map.put("img", R.drawable.xh2);
               }else if(result.level<-65){
            	   map.put("img", R.drawable.xh3);
               }else if(result.level<-55){
            	   map.put("img", R.drawable.xh4);
               }else if(result.level<-45){
            	   map.put("img", R.drawable.xh5);
               }else{
            	   map.put("img", R.drawable.xh6);
               }
            }
            map.put("scan", result);
            if (wlanManager.filter) {
                Iterator<APInfo> its = wlanManager.apInfo.iterator();
                APInfo info = null;
                while (its.hasNext()) {
                    info = its.next();
                    if (result.BSSID.equalsIgnoreCase(info.mac)) {
                        list.add(map);
                        break;
                    }
                }
            } else {
                list.add(map);
            }
        }
        if(list.size() > 0) {
        	 adapter = null;
			 adapter = new SimpleAdapter(ctx, list,
					R.layout.rssi_list_widget, new String[] { "ssid", "mac", "img",
							"level","xindao"}, new int[] { R.id.wifi_ssid, R.id.wifi_mac,
							R.id.wifi_img, R.id.wifi_level ,R.id.wifi_xindao});
			wifiView.setAdapter(adapter);
		}
	}

	private void showSortButton(final Handler handler) {
		final Dialog waitDialog = new Dialog(ctx, R.style.TRANSDIALOG);
		waitDialog.setContentView(R.layout.wifi_list_sort_button);
		waitDialog.getWindow().setBackgroundDrawableResource(
				R.color.transparent2);

		// 设置窗口里控件的透明度
		Window window = waitDialog.getWindow();
		WindowManager.LayoutParams lp = window.getAttributes();
		lp.flags = WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
		window.setGravity(Gravity.LEFT | Gravity.TOP);
		/*
		 * lp.x = 260; // 新位置X坐标 lp.y = 155; // 新位置Y坐标
		 */
		WindowManager m = ctx.getWindowManager();
		Display d = m.getDefaultDisplay(); // 获取屏幕宽、高用
		lp.x = (int) (d.getWidth() * 0.542); // 新位置X坐标 480
		lp.y = (int) (d.getHeight() * 0.194); // 新位置Y坐标 800
		// System.out.println("d.getHeight() :　d.getWidth()　＝　" + d.getHeight()
		// + " : " + d.getWidth());
		lp.alpha = 0.9f; // 透明度
		window.setAttributes(lp);

		LinearLayout linearLayout = (LinearLayout) waitDialog
				.findViewById(R.id.linearlayout_bt_sort_list);
		final ListView listView = (ListView) waitDialog
				.findViewById(R.id.bt_sort_list);
		List<String> list_buttons = new ArrayList<String>();
		String name = "默    认";
		list_buttons.add(name);
		name = "S S I D";
		list_buttons.add(name);
		name = "MAC地址";
		list_buttons.add(name);
		name = "信号强度";
		list_buttons.add(name);
		name = "信    道";
		list_buttons.add(name);

		SortButtoniListAdapter adapter = new SortButtoniListAdapter(ctx,
				list_buttons);
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				Message msg = handler.obtainMessage();
				msg.arg1 = arg2;
				msg.sendToTarget();
				waitDialog.dismiss();
			}
		});
		listView.setAdapter(adapter);
		waitDialog.setCancelable(true);
		waitDialog.setCanceledOnTouchOutside(true);
		waitDialog.show();

		final long duration = 200;
		AnimationSet animation = new AnimationSet(true);
		// 移动变化
		TranslateAnimation myAnimation_Translate;
		myAnimation_Translate = new TranslateAnimation(
				Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF,
				0.0f, Animation.RELATIVE_TO_SELF, -1.0f,
				Animation.RELATIVE_TO_SELF, 0.0f);
		myAnimation_Translate.setDuration(duration);

		animation.addAnimation(myAnimation_Translate);
		// animation.addAnimation(myAnimation_Rotate);
		animation.setFillEnabled(true);
		animation.setFillAfter(true);
		animation.setInterpolator(AnimationUtils.loadInterpolator(ctx,
				android.R.anim.accelerate_interpolator));
		linearLayout.startAnimation(animation);
	}
}
